import CryptoJS from 'crypto-js'
import JSEncrypt from 'jsencrypt'

/**
 * AES加密/解密
 * @param data {Basics} 加密/解密的值
 * @param type {String< 'en' | 'de'>} 类型(en加密 de解密)
 * @param config {Object} 配置
 * @return {Boolean}
 */
export function AES(data, type = 'en', config) {
  const configs = {
    key: '1234123412ABCDEF', // 秘钥
    iv: '', // 秘钥偏移量
    ...config
  }
  const key = CryptoJS.enc.Utf8.parse(configs.key)
  const iv = CryptoJS.enc.Utf8.parse(configs.iv)

  if (type === 'en') {
    const srcs = CryptoJS.enc.Utf8.parse(data)
    // 加密
    if (configs.iv !== '') {
      const encrypted = CryptoJS.AES.encrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.ZeroPadding })
      return CryptoJS.enc.Base64.stringify(encrypted.ciphertext)
    } else {
      const encrypted = CryptoJS.AES.encrypt(srcs, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 })
      return encrypted.toString()
    }
  } else if (type === 'de') {
    // 解密
    if (configs.iv !== '') {
      const decrypt = CryptoJS.AES.decrypt(data, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.ZeroPadding })
      return CryptoJS.enc.Utf8.stringify(decrypt).toString()
    } else {
      const decrypt = CryptoJS.AES.decrypt(data, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 })
      return CryptoJS.enc.Utf8.stringify(decrypt).toString()
    }
  }
}

/**
 * MD5加密
 * @param data {Basics} 加密的值
 * @return {Boolean}
 */
export function MD5(data) {
  return CryptoJS.MD5(data).toString()
}

/**
 * base64加密/解密
 * @param data {Basics} 加密/解密的值
 * @param type {String< 'en' | 'de'>} 类型(en加密 de解密)
 * @return {Boolean}
 */

export function Base64(data, type = 'en') {
  if (type === 'en') {
    const wordArray = CryptoJS.enc.Utf8.parse(data)
    return CryptoJS.enc.Base64.stringify(wordArray)
  } else if (type === 'de') {
    const parsedWordArray = CryptoJS.enc.Base64.parse(data)
    return parsedWordArray.toString(CryptoJS.enc.Utf8)
  }
}

// RSA加密
export function RSA(data) {
  const encrypt = new JSEncrypt()
  encrypt.setPublicKey('MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCbMNFkNFTVBejZik31vfnpzYXZklnIgQ28UxHecnYjUdlpPi7QpYOu1B8/gTg6OHSxE5qm3nC8ii0G9Vag+F4HRaLhH8oPalH3gXd21KMuD7lYaAgTel5FWvL/pc/evXPosTr0lOwhKPGkHq4UaDwE7H/tDY9k7VszC7lerU0rmwIDAQAB')
  return encrypt.encrypt(data)
}
